<?php

namespace App\B2BProject;

use Illuminate\Database\Eloquent\Model;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class AttachmentFiles extends Model
{
    protected $fillable = ['sha512', 'extension', 'local_path', 'mime_type', 'original_name', 'size'];

    public static function setNewUploadFile(UploadedFile $file, $path = '')
    {
        if ($file->isValid()) {
            $sha512    = hash_file('sha512', $file->getPathname());
            $extension = $file->guessClientExtension();
            $localName = md5($sha512) . '_' . time() . '.' . $extension;
            $mime      = $file->getMimeType();
            $origin    = $file->getClientOriginalName();
            $size      = $file->getSize();

            $target = trim(str_replace(base_path(), '',
                $file->move(base_path('storage/app/upload/attachment' . $path), $localName)), '\/');

            $new                = new static;
            $new->sha512        = $sha512;
            $new->mime_type     = $mime;
            $new->local_path    = $target;
            $new->extension     = $extension;
            $new->original_name = $origin;
            $new->size          = $size;

            $new->save();
            return $new;
        } else {
            throw new FileException('Upload error');
        }
    }
}
